#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

import os
import subprocess
import sys

if sys.argv[2:]:
    print('%s [dir]' % sys.argv[0])
    exit(1)


def getgitdir():
    curpwd = os.getcwd()
    gitdir = sys.argv[1] if sys.argv[1:] else curpwd
    gitdir = gitdir if os.path.isabs(gitdir) else os.path.join(curpwd, gitdir)
    return os.path.normpath(gitdir)


def isgitrepo(dir):
    return os.path.exists(os.path.join(dir, '.git'))


def getalldirs():
    gitdir = getgitdir()
    p = subprocess.Popen('ls ' + gitdir, shell=True, stdout=subprocess.PIPE)
    out = []
    while True:
        buff = p.stdout.readline()
        ''' when p.poll() != None, the subprocess is terminated!
        '''
        if len(buff) == 0 and p.poll() is not None:
            break
        '''the output of p.stdout.readline() or read() is a bytes buffer
        '''
        out.append(os.path.join(gitdir, buff.decode('utf-8').rstrip()))
    return out


def gitremote():
    p1 = subprocess.Popen('git remote -v', shell=True, stdout=subprocess.PIPE)
    p2 = subprocess.Popen('grep fetch', shell=True,
                          stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen("awk '{print $2}'", shell=True,
                          stdin=p2.stdout, stdout=subprocess.PIPE)
    return p3.stdout.read().decode('utf-8').rstrip()


def update_repo():
    alldirs = getalldirs()
    for dir in alldirs:
        if not isgitrepo(dir):
            continue
        os.chdir(dir)
        remote = gitremote()
        print('%s [%s]:' % (os.path.basename(dir), remote))
        p = subprocess.Popen(['git pull', '--rebase'],
                             shell=True, stdout=subprocess.PIPE)
        out, err = p.communicate()
        if err is None:
            print(out.decode('utf-8'))
        else:
            print(err)


update_repo()
